package com.alibaba.nacos.config.server.jpa;

import java.io.Serializable;
import java.net.InetAddress;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.config.server.jpa.entity.IEntity;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-12
 */
public class IdGenerator implements IdentifierGenerator {

    private static final Snowflake SNOWFLAKE;

    static {
        SNOWFLAKE = IdUtil.createSnowflake(getIpHash(), 1);
    }


    private static int getIpHash() {
        try{
            InetAddress ip = InetAddress.getLocalHost();
            String hostName = ip.getHostAddress();
            String substring = hostName.substring(hostName.lastIndexOf('.') + 1);
            int ipSurfix = Integer.parseInt(substring);
            while (ipSurfix > 31) {
                ipSurfix = ipSurfix >> 1;
            }
            return ipSurfix;
        }catch (Exception e) {
            throw new UnsupportedOperationException(e);
        }

    }


    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        IEntity entity = (IEntity) object;
        if (entity.getPk() == null) {
            return SNOWFLAKE.nextId();
        }
        return entity.getPk();
    }
}
